<template>
  <div class="page-container">
    <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="getData" />
    <table-index :table="table" @loadData="getData" />
  </div>
  <MessageModal ref="messageModalRef" />
</template>

<script setup lang="ts" name="SystemMessageList">
  import MessageModal from '../components/message-modal.vue'
  import { useTable, useFetchTableDataApi } from '@/hooks/table'
  import { getNoticeList, toNoticeDetail } from '@/api/business/message'
  import { readMsg } from '@/api/common/index'
  import { onMounted, ref, reactive, computed } from 'vue'
  import { usePageDict } from '@/hooks/useDict'
  import useNavigate from '@/hooks/useNavigate'
  import useUserStore from '@/store/modules/user'
  const userStore = useUserStore()

  const dict = usePageDict('getNoticeEnums')

  // 接口参数（不包含page信息）
  const queryParam = reactive<any>({
    noticeType: 2,
  })

  const dateTimeAttrs = {
    type: 'i-range-picker',
    attrs: {
      showTime: true,
      timePickerProps: {
        defaultValue: ['00:00:00', '23:59:59'],
      },
    },
  }

  // 查询条件
  const searchList = computed(() => {
    return [
      { label: '消息类型', prop: 'typeList', type: 'a-select', options: dict.systemTypeEnum, multiple: true },
      { label: '标题', prop: 'titleLike', type: 'a-input', maxlength: 30 },
      {
        label: '推送时间',
        prop: 'startTimeRange',
        ...dateTimeAttrs,
        change: (value = []) => {
          queryParam.sendTimeStart = value[0]
          queryParam.sendTimeEnd = value[1]
        },
      },
    ]
  })

  // 初始化
  const init = () => {
    getData(queryParam)
  }
  const messageModalRef = ref()
  // table 配置
  const table = useTable({
    columns: [
      { title: '消息类型', dataIndex: 'typeName', width: 110 },
      { title: '标题', dataIndex: 'title', width: 540 },
      { title: '推送时间', dataIndex: 'sendTime', width: 350 },
    ],
    operates: [
      {
        label: '查看',
        method: (record: any) => {
          toDetail(record)
        },
      },
    ],
  })

  // 获取列表数据，表格id已读处理
  const getData = (page: any) => {
    const fn = useFetchTableDataApi(table, queryParam, getNoticeList)
    fn(page).then((res: any) => {
      if (res.data?.length > 0) {
        let idList = res.data.map((i: any) => i.id)
        handleUpdateData(idList)
      }
    })
  }
  // 切换分页已读消息
  const handleUpdateData = (idList: any) => {
    readMsg({
      idList: idList,
    }).then(() => {
      userStore.updateUnreadMsgCount()
    })
  }

  const toDetail = (record: any) => {
    toNoticeDetail({
      id: record.id,
    }).then((res) => {
      messageModalRef.value.open(res.result)
    })
  }

  onMounted(() => {
    init()
  })
</script>

<style lang="less" scoped></style>
